package com.fan.springboot.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.fan.springboot.domain.Banner;

@Repository
public class BannerDao {

	@Autowired
	private MongoTemplate mongoTemplate;

	public void save(Banner banner) {
		mongoTemplate.save(banner);
	}

	public void delete(String id) {
		mongoTemplate.remove(new Query(Criteria.where("id").is(id)), Banner.class);
	}

	public List<Banner> findBannerListByOrderBy(String orderby) {
		List<Banner> bannerList = null;
		Query query = new Query();
		if (orderby.equals("asc")) {
			query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "sequence")));
		}

		if (orderby.equals("desc")) {
			query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "sequence")));
		}
		
		bannerList = mongoTemplate.find(query, Banner.class);

		return bannerList;
	}

	public int getPrevSequence() {
		List<Banner> bList = null;
		Query query = new Query();
		query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "sequence"))).limit(1);
		bList = mongoTemplate.find(query, Banner.class);
		if (bList.size() == 0) {
			return 0;
		} else {
			return bList.get(0).getSequence();
		}
	}

	public void updateBanner(Banner banner) {
		Query query = new Query(Criteria.where("id").is(banner.getId()));
		Update update = new Update().set("isUse", banner.getIsUse())
				.set("sequence", banner.getSequence()).set("link", banner.getLink());
		mongoTemplate.updateFirst(query, update, Banner.class);
	}
	
	//根据id查询banner对象
	public Banner findBannerById(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), Banner.class);
	}

}
